package com.blue.code.db.ftl;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.blue.code.db.bean.EntityBean;
import com.blue.core.util.ReflectionUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;

@Component
public class ServiceHandler implements Handler
{
	private static Logger logger = LoggerFactory.getLogger(ServiceHandler.class);

	@Value("${ftl.service}")
	private String service;
	@Value("${ftl.dao}")
	private String dao;
	@Value("${ftl.model}")
	private String model;
	@Value("${output.module}")
	private String module;
	
	private Template template;
	
	public ServiceHandler()
	{
	}

	@Override
	public void handle(EntityBean bean, String output, String pkg) throws Exception
	{
		Map<String, Object> root = new HashMap<>();
		root.put("module", module);
		root.put("prefix", bean.getPrefix());
		root.put("pkg", pkg + "." + service);
		root.put("daoPkg", pkg + "." + dao);
		root.put("modelPkg", pkg + "." + model);
		root.put("clazz", bean.getClazz());
		root.put("name", bean.getName());
		root.put("field", ReflectionUtil.clazzToField(bean.getClazz()));
		
		String clazz = bean.getClazz() + "Service";
		String fileName = this.output(template, root, output, service, clazz);
		logger.info("输出文件：{}", fileName);
	}

	@Override
	public void initConfiguration(Configuration conf, String ext) throws Exception
	{
		String ftl = service + ext;
		template = conf.getTemplate(ftl);
		logger.info("初始化 Service 模板：{}", ftl);
	}
}
